package com.example.consumer;

import com.alibaba.fastjson.JSON;
import com.example.entity.Order;
import com.example.entity.OrderSort;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Component
@Slf4j
public class BatchOrderConsumer {

    /**
     * 批量消费订单消息
     * 每次拉取的条数由配置决定BatchingRabbitTemplate的batchSize*SimpleRabbitListenerContainerFactory的BatchSize
     * 使用 @RabbitListener 注解监听队列  , containerFactory = "batchRabbitListenerContainerFactory"
     */
    @RabbitListener(queues = "order.batch.queue", containerFactory = "batchRabbitListenerContainerFactory", ackMode = "MANUAL")
    public void handleOrderBatch(List<Message> messages, Channel channel) {
        log.info("queue 1 received {} messages", messages.size());
        try {
            for (Message message : messages) {
                String messageText = new String(message.getBody(), StandardCharsets.UTF_8);
                //处理任务
                Order order = JSON.parseObject(messageText, Order.class);
                log.info("用户中心同步消息：{}", JSON.toJSONString( order));

            }

            // 修复1: 正确获取最后一条消息的deliveryTag
            if (!messages.isEmpty()) {
                long lastDeliveryTag = messages.get(messages.size() - 1)
                        .getMessageProperties().getDeliveryTag();
                // 修复2: 添加Channel状态检查和异常处理
                if (channel != null && channel.isOpen()) {
                    channel.basicAck(lastDeliveryTag, true); // 批量确认
                }
            }
        } catch (Exception e) {
            log.error("处理接受日志异常：{}", e.getMessage(), e);
            // 添加消息拒绝逻辑
            try {
                if (!messages.isEmpty() && channel != null && channel.isOpen()) {
                    long lastDeliveryTag = messages.get(messages.size() - 1)
                            .getMessageProperties().getDeliveryTag();
                    channel.basicNack(lastDeliveryTag, true, false);
                }
            } catch (Exception ex) {
                log.error("消息拒绝失败：{}", ex.getMessage(), ex);
            }
        }
    }
}